package com.my.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.my.apis.schedule.IScheduleClient;
import com.my.common.constans.ScheduleConstants;
import com.my.common.redis.CacheService;
import com.my.model.common.dtos.ResponseResult;
import com.my.model.common.enums.TaskTypeEnum;
import com.my.model.schedule.dtos.Task;
import com.my.model.wemedia.pojos.WmNews;
import com.my.utils.common.ProtostuffUtil;
import com.my.wemedia.service.WmAutoScanService;
import com.my.wemedia.service.WmNewsTaskService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.Calendar;
import java.util.Date;

@Slf4j
@Service
public class WmNewsTaskServiceImpl implements WmNewsTaskService {
    @Autowired
    private IScheduleClient scheduleClient;
    /**
     * 添加任务到延迟队列
     * @param id 文章id
     * @param publishTime  文章发布时间
     */
    @Override
    @Async
    public void addNewsToTask(Integer id, Date publishTime) {
        log.info("添加任务到延迟服务中---begin");

        Task task = new Task();
        task.setExecuteTime(publishTime.getTime());
        task.setTaskType(TaskTypeEnum.NEWS_SCAN_TIME.getTaskType());
        task.setPriority(TaskTypeEnum.NEWS_SCAN_TIME.getPriority());
        WmNews wmNews = new WmNews();
        wmNews.setId(id);
        task.setParameters(ProtostuffUtil.serialize(wmNews));

        scheduleClient.addTask(task);

        log.info("添加任务到延迟服务中---end");
    }

    @Autowired
    private WmAutoScanService wmAutoScanService;
    @Autowired
    private CacheService cacheService;
    /**
     * 消费任务
     */
    @Override
    @Scheduled(fixedRate = 2000)  //每两秒执行一次
    public void scanNewsByTask() {
        ResponseResult responseResult = scheduleClient.poll(TaskTypeEnum.NEWS_SCAN_TIME.getTaskType(), TaskTypeEnum.NEWS_SCAN_TIME.getPriority());
        if(responseResult.getCode().equals(200) && responseResult.getData() != null) {
            log.info("文章审核---消费任务执行---begin");

            String json_str = JSON.toJSONString(responseResult.getData());
            Task task = JSON.parseObject(json_str,Task.class);
            byte[] parameters = task.getParameters();
            //反序列化
            WmNews wmNews = ProtostuffUtil.deserialize(parameters, WmNews.class);

            try {
                wmAutoScanService.AutoScanTextAndImage(wmNews.getId(), task.getTaskId());
            } catch (Exception e) {
                log.warn("审核失败，将于5分钟之后再次尝试");
                /* //文章未能成功审核，将数据加入ZSet，5分钟之后再重新尝试
                //1.构造key
                String key = task.getTaskType() + "_" + task.getPriority();
                //2.获取5分钟之后的时间
                Calendar calendar = Calendar.getInstance();
                calendar.add(Calendar.MINUTE,5);
                long nextScheduleTime = calendar.getTimeInMillis();

                //3.将数据重新加入
                cacheService.zAdd(ScheduleConstants.FUTURE + key,JSON.toJSONString(task),nextScheduleTime); */
                e.printStackTrace();
            }

            log.info("文章审核---消费任务执行---end");
        }
    }
}
